$(function () {
    $('#cerTb').datagrid({
        rownumbers: true,//显示行号
        striped: true,
        fit: true,
        singleSelect: true,
        sortOrder: true,
        fitColumns: true,
        pagination: true,
        toolbar: '#toolbar',
        url: ROOT_PATH + '/train/certificate/CerTable.shtml',
        queryParams: {
            sort: 'addTime',
            order: 'desc'
        },
        columns: [[
            {
                field: 'id', checkbox: true
            },
            {
                field: 'realName', title: '姓名', width: 100, formatter: function (value, row, index) {
                return "<a href='javascript:void(0)' class='easyui-linkbutton text-primary' plain='true'   onclick='infoCertificate(\"" + row.id + "\");'>" + row.realName + "</a>";
            }
            },
            {
                field: 'CompanyName',
                title: '工作单位',
                width: 100,
                formatter: function (value, row, index) {
                    var name = '';
                    if (row.userDepartmentList && row.userDepartmentList.length > 0) {
                        for (var index in row.userDepartmentList) {
                            if (row.userDepartmentList[index].deptName != null) {
                                name += ',' + row.userDepartmentList[index].deptName;
                            }
                        }
                        return name.substring(1);
                    } else {
                        return '';
                    }
                }
            },
            {field: 'certificateTypeName', title: '证书种类', width: 130},
            {field: 'name', title: '证书名称', width: 130},
            {field: 'certificateTime', title: '发证/复审/换证日期', width: 180},
            {
                field: 'zt', title: '状态', width: 60, formatter: function (value, row, index) {
                var b1 = false;
                var b2 = false;
                if (typeof (row.nextReviewTime) == 'undefined' || row.nextReviewTime == null) {
                    b1 = true;
                } else {
                    var now = new Date();
                    var dateR = new Date(row.nextReviewTime);
                    if (dateR > now) {
                        b1 = true;
                    }
                }
                if (typeof (row.nextChangedTime) == 'undefined' || row.nextChangedTime == null) {
                    b2 = true;
                } else {
                    var now = new Date();
                    var dateC = new Date(row.nextChangedTime);
                    if (dateC > now) {
                        b2 = true;
                    }
                }
                if (b1 && b2) {
                    return '<span class="color-success text-white" style="padding: 3px;border-radius:5px;">有效</span>';
                } else {
                    return '<span class="color-important text-white" style="padding: 3px;border-radius:5px;">无效</span>';
                }
            }
            },
            {field: 'reviewCycle', title: '复审周期(年)', width: 120},
            {
                field: 'nextReviewTime', title: '应复审日期', width: 100, styler: function (value, row) {
                if (typeof row.nextReviewTime == 'undefined' || row.nextReviewTime == null) {
                    return;
                }
                return getStyleAfterCheckDate(row.nextReviewTime);
            }
            },
            {field: 'changedCycle', title: '换证周期(年)', width: 120},
            {
                field: 'nextChangedTime', title: '应换证日期', width: 100, styler: function (value, row) {
                if (typeof row.nextChangedTime == 'undefined' || row.nextChangedTime == null) {
                    return;
                }
                return getStyleAfterCheckDate(row.nextChangedTime);
            }
            },
            {field: 'num', title: '证书编号', width: 100},
            {field: 'issueAuthority', title: '发证机构', width: 100},
            {field: 'addUserName', title: '登记人', width: 100},
            {field: 'addDeptName', title: '登记部门', width: 100},
            {field: 'addTime', title: '登记时间', width: 100}
        ]]
    });
    $('#btn_tr_certificate_add').on('click', function () {
        addCertificate();
    });
    $('#btn_tr_certificate_delete').on('click', function () {
        deleteCertificate();
    });
    $('#btn_tr_certificate_edit').on('click', function () {
        editCertificate();
    });
    $('#btn_advanced_search').on("click", function () {
        $('#queryForm2').toggle();
        $('#cerTb').datagrid('resize');
    });
    $('#btn_clear').on("click", function () {
        $('#queryForm1').form('reset');
        $('#queryForm2').form('reset');
    });
    var TRAIN_ZSTYPE = CONSTANT.DictionaryTypeDefConstants.TRAIN_ZSTYPE;//证书类型(数据字典)
    queryComboData(TRAIN_ZSTYPE, 'certificateTypeId');

    /**
     * 绑定人员选择事件
     */
    $("#searchAddUser").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                add_userId_func();
            }
        }, {
            iconCls: 'icon-remove',
            handler: function (e) {
                $(e.data.target).textbox('clear');

            }
        }]
    });
    $("#realName").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                add_userIdCer_func();
            }
        }, {
            iconCls: 'icon-remove',
            handler: function (e) {
                $(e.data.target).textbox('clear');

            }
        }]
    });
    queryDepartmentTree();
});
var getStyleAfterCheckDate = function (date) {
    var now = new Date();
    date = new Date(date);
    //var oneMonthAgo = new Date(date.valueOf() - 30 * 24 * 60 * 60 * 1000);
    if (date < now) {
        return 'background-color:#ff4d4d;';
    }

    var addDate = new Date(date);
    addDate = addDate.valueOf();
    addDate = addDate + 90 * 24 * 60 * 60 * 1000;
    addDate = new Date(addDate);
    if (addDate < now) {
        return 'background-color:#f5d252;';
    }



};
var add_userId_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {
            getSelectedUser(data);
        }
    });
};
var add_userIdCer_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {
            getSelectedUserCer(data);
        }
    });
};
/**
 * 人员信息选择
 */
var getSelectedUser = function (data) {
    $("#searchAddUser").textbox('setValue', data[0].realName).textbox('setText', data[0].realName);
};
var getSelectedUserCer = function (data) {
    $("#realName").textbox('setValue', data[0].realName).textbox('setText', data[0].realName);
};
function queryDepartmentTree() {
    $.ajax({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data: {parentId: 0},//将表单数据序列化
        type: "POST",
        dataType: "json",
        success: function (result) {
            deptCom('searchAddDept', result);
            deptCom('deptIdName', result);
        }
    });
}
function deptCom(id, result) {
    var deptId = '#' + id;
    $(deptId).combotree(
        {
            data: result,
            prompt: '请选择',
            require: true,
            loadFilter: function (data) {
                var newData = new Array();
                newData.push({id: "", text: '请选择'});
                newData.push(data[0]);
                return newData;
            }
        }
    );
}

function pageComData(id, data) {
    var pageId = '#' + id;
    $(pageId).combobox({
        data: data,
        valueField: 'id',
        textField: 'text',
        editable: false,
        panelHeight: '200',
        selectOnNavigation: true,
    });
}
function queryComboData(code, queryId) {
    var EMPTY_OPTION = {
        id: '',
        text: '请选择'
    };
    var pageId = '#' + queryId;
    $.ajax({
        type: 'post',
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',
        data: {code: code},
        dataType: "json",
        success: function (result) {
            $(pageId).combobox({
                loadFilter: function (data) {
                    data.unshift(EMPTY_OPTION);
                    return data;
                },
                data: result,
                valueField: 'id',
                textField: 'text',
                editable: false,
                panelHeight: '200',
                onSelect: function (record) {
                }
            });
        }
    });
}
/**
 * 重新加载表格
 */
function reLoadData() {
    $('#cerTb').datagrid('clearSelections');
    var queryParams1 = $('#queryForm1').serializeJson();
    var queryParams2 = $('#queryForm2').serializeJson();
    var queryParams = $.extend(queryParams1, queryParams2);
    queryParams["sort"] = 'addTime';
    queryParams["order"] = 'desc';
    $('#cerTb').datagrid('options').queryParams = queryParams;
    $("#cerTb").datagrid('reload', ROOT_PATH + '/train/certificate/CerTable.shtml');
}
function queryYearthList(id) {
    var date = new Date();
    var year = date.getFullYear();
    var yearthData = new Array();
    //yearthData.push({id:"",text:"请选择"});
    for (var i = 0; i < 6; i++) {
        var y = {id: year - i, text: (year - i) + '年'}
        yearthData.push(y);
    }
    $('#' + id).combobox(
        {
            data: yearthData,
            valueField: 'id',
            textField: 'text'
        }
    );
}
/**
 * 打开弹框
 * @param title
 * @param content
 */
function openLayers(title, content) {
    WindowManager.openLayer({
        type: 2,
        resize: false,
        title: title,
        area: ['1150px', '80%'],
        content: content,
        callBack: function (data) {
            if (data) {
                reLoadData();
            }
        }
    });
}
/**
 * 打开新建
 */
function addCertificate() {
    var title = '证书登记';
    var content = ROOT_PATH + '/train/certificate/add.shtml?resourceId=' + $.getQueryParam('resourceId');
    openLayers(title, content);
}
/**
 * 删除
 */
function deleteCertificate() {
    var rows = $('#cerTb').datagrid('getSelections');
    if (rows.length == 0) {
        layer.alert("请选择计划下的培训记录进行删除！");
        return;
    } else {
        var id = rows[0].id;
        layer.confirm('是否确定撤销当前培训记录？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            $.ajax({
                type: 'post',
                url: ROOT_PATH + '/train/certificate/deleteById.shtml',
                data: {id: id},
                dataType: "json",
                success: function (result) {
                    if (result.success) {
                        $('#cerTb').datagrid('clearSelections');
                        reLoadData();
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 1000
                        });
                    }
                    else {
                        layer.msg('删除失败', {
                            icon: 2,
                            time: 1000
                        });
                    }
                }
            });
        });
    }
}
/**
 * 编辑
 */
function editCertificate() {
    var rows = $('#cerTb').datagrid('getSelections');
    if (rows.length == 0) {
        layer.alert("选择需要编辑的行！");
        return;
    }
    var id = rows[0].id;
    var title = '编辑证书信息';
    var content = ROOT_PATH + '/train/certificate/info.shtml?resourceId=' + $.getQueryParam('resourceId') + '&id=' + id + '&type=edit';
    openLayers(title, content);
}
function infoCertificate(id) {
    var title = '证书登记详情';
    var content = ROOT_PATH + '/train/certificate/info.shtml?resourceId=' + $.getQueryParam('resourceId') + '&id=' + id + '&type=info';
    openLayers(title, content);
}

